<template>
	<el-main class="bg edit_wrap">
		<!-- 如果无权限，显示提示信息 -->
		<div v-if="!is_view()" style="padding: 20px; text-align: center; color: #999;">
			<p>您没有查看此页面的权限</p>
			<p style="font-size: 12px; margin-top: 10px;">请联系管理员获取相应权限</p>
		</div>
		<el-form ref="form" :model="form" status-icon label-width="120px" v-else>
			<!-- 如果表单为空，显示提示 -->
			<div v-if="!form || Object.keys(form).length === 0 || !form['user_participation_id']" style="padding: 20px; text-align: center; color: #999;">
				<p>正在加载数据...</p>
			</div>
			<template v-if="form && form['user_participation_id']">
							<el-col v-if="user_group === '管理员' || $check_field('get','meeting_number') || $check_field('add','meeting_number') || $check_field('set','meeting_number')" :xs="24" :sm="12" :lg="8" class="el_form_item_warp">
				<el-form-item label="会议编号" prop="meeting_number">
												<el-input id="meeting_number" v-model="form['meeting_number']" placeholder="请输入会议编号"
							  v-if="user_group === '管理员' || (form['user_participation_id'] && $check_field('set','meeting_number')) || (!form['user_participation_id'] && $check_field('add','meeting_number'))" :disabled="disabledObj['meeting_number_isDisabled']"></el-input>
					<div v-else-if="$check_field('get','meeting_number')">{{form['meeting_number']}}</div>
											</el-form-item>
			</el-col>
								<el-col v-if="user_group === '管理员' || $check_field('get','conference_name') || $check_field('add','conference_name') || $check_field('set','conference_name')" :xs="24" :sm="12" :lg="8" class="el_form_item_warp">
				<el-form-item label="会议名称" prop="conference_name">
												<el-input id="conference_name" :value="getChineseText(form['conference_name'])" placeholder="请输入会议名称"
							  v-if="user_group === '管理员' || (form['user_participation_id'] && $check_field('set','conference_name')) || (!form['user_participation_id'] && $check_field('add','conference_name'))" :disabled="true"></el-input>
					<div v-else-if="$check_field('get','conference_name')">{{getChineseText(form['conference_name'])}}</div>
											</el-form-item>
			</el-col>
								<el-col v-if="user_group === '管理员' || $check_field('get','meeting_type') || $check_field('add','meeting_type') || $check_field('set','meeting_type')" :xs="24" :sm="12" :lg="8" class="el_form_item_warp">
				<el-form-item label="会议类型" prop="meeting_type">
												<el-input id="meeting_type" :value="getChineseText(form['meeting_type'])" placeholder="请输入会议类型"
							  v-if="user_group === '管理员' || (form['user_participation_id'] && $check_field('set','meeting_type')) || (!form['user_participation_id'] && $check_field('add','meeting_type'))" :disabled="true"></el-input>
					<div v-else-if="$check_field('get','meeting_type')">{{getChineseText(form['meeting_type'])}}</div>
											</el-form-item>
			</el-col>
								<el-col v-if="user_group === '管理员' || $check_field('get','meeting_time') || $check_field('add','meeting_time') || $check_field('set','meeting_time')" :xs="24" :sm="12" :lg="8" class="el_form_item_warp">
				<el-form-item label="会议时间" prop="meeting_time">
												<el-input id="meeting_time" v-model="form['meeting_time']" placeholder="请输入会议时间"
							  v-if="user_group === '管理员' || (form['user_participation_id'] && $check_field('set','meeting_time')) || (!form['user_participation_id'] && $check_field('add','meeting_time'))" :disabled="disabledObj['meeting_time_isDisabled']"></el-input>
					<div v-else-if="$check_field('get','meeting_time')">{{form['meeting_time']}}</div>
											</el-form-item>
			</el-col>
								<el-col v-if="user_group === '管理员' || $check_field('get','meeting_venue') || $check_field('add','meeting_venue') || $check_field('set','meeting_venue')" :xs="24" :sm="12" :lg="8" class="el_form_item_warp">
				<el-form-item label="会议地点" prop="meeting_venue">
												<el-input id="meeting_venue" :value="getChineseText(form['meeting_venue'])" placeholder="请输入会议地点"
							  v-if="user_group === '管理员' || (form['user_participation_id'] && $check_field('set','meeting_venue')) || (!form['user_participation_id'] && $check_field('add','meeting_venue'))" :disabled="true"></el-input>
					<div v-else-if="$check_field('get','meeting_venue')">{{getChineseText(form['meeting_venue'])}}</div>
											</el-form-item>
			</el-col>
								<el-col v-if="user_group === '管理员' || $check_field('get','amount_of_participation') || $check_field('add','amount_of_participation') || $check_field('set','amount_of_participation')" :xs="24" :sm="12" :lg="8" class="el_form_item_warp">
				<el-form-item label="参会金额" prop="amount_of_participation">
								<el-input-number id="amount_of_participation" v-model.number="form['amount_of_participation']"
						v-if="user_group === '管理员' || (form['user_participation_id'] && $check_field('set','amount_of_participation')) || (!form['user_participation_id'] && $check_field('add','amount_of_participation'))" :disabled="disabledObj['amount_of_participation_isDisabled']"></el-input-number>
					<div v-else-if="$check_field('get','amount_of_participation')">{{form['amount_of_participation']}}</div>
							</el-form-item>
			</el-col>
								<el-col v-if="user_group === '管理员' || $check_field('get','participants') || $check_field('add','participants') || $check_field('set','participants')" :xs="24" :sm="12" :lg="8" class="el_form_item_warp">
				<el-form-item label="参会用户" prop="participants">
																		<div v-if="user_group !== '管理员'">
							{{ get_user_session_participants(form['participants']) }}
							<!--<el-input id="business_name" v-model="form['participants']" placeholder="请输入参会用户"-->
							<!--v-if="user_group === '管理员' || (form['user_participation_id'] && $check_field('set','participants')) || (!form['user_participation_id'] && $check_field('add','participants'))" :disabled="disabledObj['participants_isDisabled']"></el-input>-->
							<!--<div v-else-if="$check_field('get','participants')">{{form['participants']}}</div>-->
							<el-select v-if="user_group === '管理员' || (form['user_participation_id'] && $check_field('set','participants')) || (!form['user_participation_id'] && $check_field('add','participants'))" id="participants" v-model="form['participants']" :disabled="disabledObj['participants_isDisabled']">
								<el-option v-for="o in list_user_participants" :key="o['username']" :label="o['nickname'] + '-' + o['username']"
										   :value="o['user_id']">
								</el-option>
							</el-select>
							<el-select v-else-if="$check_field('get','participants')" id="participants" v-model="form['participants']" :disabled="true">
								<el-option v-for="o in list_user_participants" :key="o['username']" :label="o['nickname'] + '-' + o['username']"
										   :value="o['user_id']">
								</el-option>
							</el-select>
						</div>
						<el-select v-else id="participants" v-model="form['participants']" :disabled="disabledObj['participants_isDisabled']">
							<el-option v-for="o in list_user_participants" :key="o['username']" :label="o['nickname'] + '-' + o['username']"
									   :value="o['user_id']">
							</el-option>
						</el-select>
																</el-form-item>
			</el-col>
								<el-col v-if="user_group === '管理员' || $check_field('get','user_name') || $check_field('add','user_name') || $check_field('set','user_name')" :xs="24" :sm="12" :lg="8" class="el_form_item_warp">
				<el-form-item label="用户姓名" prop="user_name">
												<el-input id="user_name" v-model="form['user_name']" placeholder="请输入用户姓名"
							  v-if="user_group === '管理员' || (form['user_participation_id'] && $check_field('set','user_name')) || (!form['user_participation_id'] && $check_field('add','user_name'))" :disabled="disabledObj['user_name_isDisabled']"></el-input>
					<div v-else-if="$check_field('get','user_name')">{{form['user_name']}}</div>
											</el-form-item>
			</el-col>
								<el-col v-if="user_group === '管理员' || $check_field('get','accommodation_or_not') || $check_field('add','accommodation_or_not') || $check_field('set','accommodation_or_not')" :xs="24" :sm="12" :lg="8" class="el_form_item_warp">
				<el-form-item label="是否住宿" prop="accommodation_or_not">
								<el-select id="accommodation_or_not" v-model="form['accommodation_or_not']"
						v-if="user_group === '管理员' || (form['user_participation_id'] && $check_field('set','accommodation_or_not')) || (!form['user_participation_id'] && $check_field('add','accommodation_or_not'))">
						<el-option v-for="o in list_accommodation_or_not" :key="o" :label="o" :value="o">
						</el-option>
					</el-select>
					<div v-else-if="$check_field('get','accommodation_or_not')">{{form['accommodation_or_not']}}</div>
							</el-form-item>
			</el-col>
							<el-col :xs="24" :sm="12" :lg="8" class="el_form_item_warp">
				<el-form-item label="审核状态" prop="examine_state">
					<el-select id="examine_state" v-model="form['examine_state']"
						v-if="user_group === '管理员' || (form['examine_state'] && $check_examine()) || (!form['examine_state'] && $check_examine())">
						<el-option key="未审核" label="未审核" value="未审核"></el-option>
						<el-option key="已通过" label="已通过" value="已通过"></el-option>
						<el-option key="未通过" label="未通过" value="未通过"></el-option>
					</el-select>
					<div v-else>{{form["examine_state"]}}</div>
				</el-form-item>
			</el-col>
		
	
	
	
	
	
	
			<el-col :xs="24" :sm="12" :lg="8" class="el_form_btn_warp">
				<el-form-item>
					<el-button type="primary" @click="submit()">提交</el-button>
					<el-button @click="cancel()">取消</el-button>
				</el-form-item>
			</el-col>
			</template>

		</el-form>
	</el-main>
</template>

<script>
	import mixin from "@/mixins/page.js";
	import mixinI18n from "@/mixins/i18n.js";

	export default {
		mixins: [mixin, mixinI18n],
		data() {
			return {
				field: "user_participation_id",
				url_add: "~/api/user_participation/add?",
				url_set: "~/api/user_participation/set?",
				url_get_obj: "~/api/user_participation/get_obj?",
				url_upload: "~/api/user_participation/upload?",

				query: {
					"user_participation_id": 0,
				},

				form: {
								"meeting_number":  '', // 会议编号（仅显示，不保存）
										"conference_name":  '', // 会议名称（仅显示，不保存）
										"meeting_type":  '', // 会议类型（仅显示，不保存）
										"meeting_time":  '', // 会议时间（仅显示，不保存）
										"meeting_venue":  '', // 会议地点（仅显示，不保存）
										"meeting_information_id": 0, // 会议ID（必须保存）
										"amount_of_participation":  0, // 参会金额
										"participants": 0, // 参会用户
										"user_name":  '', // 用户姓名（仅显示，不保存）
										"accommodation_or_not":  '', // 是否住宿
									"examine_state": "未审核",
								"user_participation_id": 0, // ID
						
				},
				disabledObj:{
								"meeting_number_isDisabled": false,
										"conference_name_isDisabled": false,
										"meeting_type_isDisabled": false,
										"meeting_time_isDisabled": false,
										"meeting_venue_isDisabled": false,
					          			"amount_of_participation_isDisabled": false,
										"participants_isDisabled": false,
										"user_name_isDisabled": false,
										"accommodation_or_not_isDisabled": false,
										},

	
		
		
		
		
		
		
					// 用户列表
				list_user_participants: [],
						// 用户组
				group_user_participants: "",
				
						// 是否住宿选项列表
				list_accommodation_or_not: ['是','否'],
	
	
			}
		},
		methods: {


	
	
			
	
			
	
			
	
			
	
			
	
			
	
				/**
			 * 获取普通用户用户列表
			 */
			async get_list_user_participants() {
                // if(this.user_group !== "管理员" && this.form["participants"] === 0) {
                //     this.form["participants"] = this.user.user_id;
                // }
                var json = await this.$get("~/api/user/get_list?user_group=普通用户");
                if(json.result && json.result.list){
                    this.list_user_participants = json.result.list;
                }
                else if(json.error){
                    console.error(json.error);
                }
			},
					/**
			 * 获取普通用户用户组
			 */
			async get_group_user_participants() {
							this.form["participants"] = this.user.user_id;
							var json = await this.$get("~/api/user_group/get_obj?name=普通用户");
				if(json.result && json.result.obj){
					this.group_user_participants = json.result.obj;
				}
				else if(json.error){
					console.error(json.error);
				}
			},
			get_user_session_participants(id){
				var _this = this;
				var user_id = {"user_id":id}
				var url = "~/api/"+_this.group_user_participants.source_table+"/get_obj?"
				this.$get(url, user_id, function(res) {
					if (res.result && res.result.obj) {
						var arr = []
						for (let key in res.result.obj) {
							arr.push(key)
						}
						var arrForm = []
									for (let key in _this.form) {
							arrForm.push(key)
						}
												_this.form["participants"] = id
									_this.disabledObj['participants' + '_isDisabled'] = true
						for (var i=0;i<arr.length;i++){
						  if (arr[i]!=='examine_state' && arr[i]!=='examine_reply') {
							for (var j = 0; j < arrForm.length; j++) {
							  if (arr[i] === arrForm[j]) {
								if (arr[i] !== "participants") {
			                      _this.form[arrForm[j]] = res.result.obj[arr[i]]
			                      _this.disabledObj[arrForm[j] + '_isDisabled'] = true
								  break;
								} else {
								  _this.disabledObj[arrForm[j] + '_isDisabled'] = true
								}
							  }
							}
						  }
						}
					}
				});
			},
					get_user_participants(id){
				var obj = this.list_user_participants.getObj({"user_id":id});
				var ret = "";
				if(obj){
					if(obj.nickname){
						ret = obj.nickname;}
					else{
						ret = obj.username;
					}
				}
				return ret;
			},
			
	
			
	
		
			/**
			 * 获取对象之前
			 * @param {Object} param
			 */
			get_obj_before(param) {
				var form = "";
												// 获取缓存数据附加
				form = $.db.get("form");
							$.push(this.form ,form);
																																																
				if(this.form && form){
					Object.keys(this.form).forEach(key => {
						Object.keys(form).forEach(dbKey => {
							// if(dbKey === "charging_standard"){
							// 	this.form['charging_rules'] = form[dbKey];
							// 	this.disabledObj['charging_rules_isDisabled'] = true;
							// };
							if(key === dbKey){
								this.disabledObj[key+'_isDisabled'] = true;
							}
						})
					})
				}
																						$.db.del("form");
				return param;
			},

			/**
			 * 获取对象之后
			 * @param {Object} json
			 * @param {Object} func
			 */
			get_obj_after(json, func){
				// 确保 meeting_information_id 和 user_name 正确填充到表单中
				if (json.result && json.result.obj) {
					const obj = json.result.obj;
					
					// 确保 meeting_information_id 存在（编辑时必须）
					if (obj.meeting_information_id) {
						this.form['meeting_information_id'] = obj.meeting_information_id;
					} else {
						// 尝试从 result 对象中获取（可能在后端设置到了 resultMap 而不是 obj）
						const resultObj = json.result;
						if (resultObj.meeting_information_id) {
							this.form['meeting_information_id'] = resultObj.meeting_information_id;
						}
					}
					
					// 优先使用后端返回的 user_name（可能在 obj 或 result 中）
					let userName = null;
					if (obj.user_name) {
						userName = obj.user_name;
					} else if (json.result.user_name) {
						userName = json.result.user_name;
					}
					
					// 如果后端没有提供 user_name，从 attendees 中提取
					if (!userName && obj.attendees && Array.isArray(obj.attendees) && obj.attendees.length > 0) {
						const firstAttendee = obj.attendees[0];
						if (firstAttendee) {
							// 处理不同的数据结构
							if (typeof firstAttendee === 'object') {
								userName = firstAttendee.name || firstAttendee['name'] || 
										   firstAttendee.attendee_name || firstAttendee['attendee_name'];
							}
						}
					}
					
					// 设置 user_name 到表单
					if (userName) {
						this.form['user_name'] = userName;
					}
					
					// 从 attendees 中提取并设置 accommodation_or_not
					if (obj.attendees && Array.isArray(obj.attendees) && obj.attendees.length > 0) {
						const hasAccommodation = obj.attendees.some(a => {
							if (!a || typeof a !== 'object') return false;
							const acc = a.accommodation || a['accommodation'];
							return acc === 1 || acc === '1' || acc === true || acc === 'true' || acc === '是';
						});
						if (!obj.accommodation_or_not || obj.accommodation_or_not === '') {
							this.form['accommodation_or_not'] = hasAccommodation ? '是' : '否';
						}
					}
					
				}
			},

			/**
			 * 提交前事件 - 移除冗余字段
			 * @param {Object} param 提交参数
			 */
			submit_before(param) {
				// 调用父类的 submit_before（处理日期格式等）
				var pm = this.$options.mixins[0].methods.submit_before.call(this, param);
				
				// 确保 meeting_information_id 存在（如果不存在，尝试从 form 中恢复）
				if (!pm.meeting_information_id || pm.meeting_information_id === 0) {
					if (this.form.meeting_information_id) {
						pm.meeting_information_id = this.form.meeting_information_id;
					}
				}
				
				// 移除冗余字段（这些字段已经不在 user_participation 表中了）
				if (pm) {
					delete pm.meeting_number;
					delete pm.conference_name;
					delete pm.meeting_type;
					delete pm.meeting_time;
					delete pm.meeting_venue;
					// 重要：user_name 字段已经从数据库表中移除，必须删除，否则会导致 SQL 错误
					delete pm.user_name;
				}
				
				// 处理 accommodation_or_not：如果是字符串"是"/"否"，转换为整数
				if (pm && pm.accommodation_or_not !== undefined && pm.accommodation_or_not !== null) {
					const accValue = pm.accommodation_or_not;
					if (typeof accValue === 'string') {
						if (accValue === '是' || accValue === '1' || accValue === 'true') {
							pm.accommodation_or_not = 1;
						} else {
							pm.accommodation_or_not = 0;
						}
					}
				}
				
				console.log('submit_before 处理后的参数:', pm);
				return pm;
			},
			
			/**
			 * 提交前验证事件
			 * @param {Object} 请求参数
			 * @return {String} 验证成功返回null, 失败返回错误提示
			 */
			submit_check(param) {
				let msg = null;
				// 验证必要字段
				if (!param.participants || param.participants === 0) {
					msg = '请选择参会用户';
				}
				// 如果是新建（没有 user_participation_id），必须要有 meeting_information_id
				// 如果是编辑（有 user_participation_id），meeting_information_id 应该已经存在
				if (!param.user_participation_id || param.user_participation_id === 0) {
					// 新建时，如果没有 meeting_information_id，提示错误
					if (!param.meeting_information_id || param.meeting_information_id === 0) {
						msg = msg || '缺少会议信息，请选择会议';
					}
				}
				// 编辑时，如果 meeting_information_id 不存在，尝试从 form 中获取（可能在编辑时被移除）
				if (param.user_participation_id && param.user_participation_id !== 0) {
					if (!param.meeting_information_id || param.meeting_information_id === 0) {
						// 尝试从 this.form 中恢复
						if (this.form.meeting_information_id) {
							param.meeting_information_id = this.form.meeting_information_id;
							console.log('恢复 meeting_information_id:', param.meeting_information_id);
						}
					}
				}
				return msg;
			},

			is_view(){
				var bl = this.user_group == "管理员";

				if(!bl){
					bl = this.$check_action('/user_participation/table','add');
					console.log(bl ? "你有表格添加权限视作有添加权限" : "你没有表格添加权限");
				}
				if(!bl){
					bl = this.$check_action('/user_participation/table','set');
					console.log(bl ? "你有表格添加权限视作有修改权限" : "你没有表格修改权限");
				}
				if(!bl){
					bl = this.$check_action('/user_participation/view','add');
					console.log(bl ? "你有视图添加权限视作有添加权限" : "你没有视图添加权限");
				}
				if(!bl){
					bl = this.$check_action('/user_participation/view','set');
					console.log(bl ? "你有视图修改权限视作有修改权限" : "你没有视图修改权限");
				}
				if(!bl){
					bl = this.$check_action('/user_participation/view','get');
					console.log(bl ? "你有视图查询权限视作有查询权限" : "你没有视图查询权限");
				}
				// 如果以上权限都没有，检查是否有表格的get权限（至少能查看列表）
				if(!bl){
					bl = this.$check_action('/user_participation/table','get');
					console.log(bl ? "你有表格查询权限视作有查询权限" : "你没有表格查询权限");
				}

				console.log(bl ? "具有当前页面的查看权，请注意这不代表你有字段的查看权" : "无权查看当前页，请注意即便有字段查询权限没有页面查询权限也不行");

				return bl;
			},
			/**
			 * 上传文件
			 * @param {Object} param
			 */
			uploadimg(param) {
				this.uploadFile(param.file, "avatar");
			},
			// 获取中文文本（从双语JSON中提取）
			getChineseText(str) {
				if (!str) return '';
				try {
					const json = JSON.parse(str);
					if (json && typeof json === 'object' && json.zh) {
						return json.zh;
					}
				} catch (e) {
					// 不是 JSON 格式，直接返回原值（默认为中文）
				}
				return str;
			}

		},
		created() {
																	this.get_list_user_participants();
					this.get_group_user_participants();
									},
	}
</script>

<style>
	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		line-height: 178px;
		text-align: center;
	}

	.avatar {
		width: 178px;
		height: 178px;
		display: block;
	}




</style>
